package com.ruoyi.web.core.config.mqtt;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.IMqttMessageListener;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.springframework.beans.factory.annotation.Autowired;

import java.nio.charset.StandardCharsets;

/**
 * @author chmj
 * @version V1.0
 * @Package com.radar.util.mqtt
 * @Copyright 2022/9/13 16:53 汇博医疗股份有限公司
 */
@Slf4j
public class MqttUtil {

    @Autowired   //这里进行了注入操作
    private MessageListener messageListener;

    /**
     *   发送消息
     *   @param topic 主题
     *   @param data 消息内容
     */
    public static void send(String topic, Object data){
        // 获取客户端实例
        MqttClient client = MqttFactory.getInstance();
        ObjectMapper mapper = new ObjectMapper();
        try {
            // 转换消息为json字符串
            String json = mapper.writeValueAsString(data);
            client.publish(topic, new MqttMessage(json.getBytes(StandardCharsets.UTF_8)));
        } catch (JsonProcessingException e) {
            log.error("[MQTT]:主题{}发送消息转换json失败", topic);
        } catch (Exception e) {
            log.error("[MQTT]:主题{}发送消息失败", topic);
        }
    }


    /**
     * 订阅主题
     * @param topic 主题
     * @param listener 消息监听处理器
     */
    public static void subscribe(String topic, IMqttMessageListener listener) {
        MqttClient client = MqttFactory.getInstance();
        try {
            client.subscribe(topic, listener);
        } catch (MqttException e) {
            log.error("[MQTT]:订阅主题{}失败", topic);
        }
    }
}
